package me.flyray.crm.core.biz.platform;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.flyray.common.exception.BusinessException;
import me.flyray.common.msg.ResponseCode;
import me.flyray.common.util.SnowFlake;
import me.flyray.common.vo.admin.AddPlatformOrMerchantRequest;
import me.flyray.crm.core.api.BusinessRestApi;
import me.flyray.crm.facade.feignclient.modules.admin.AdminUserServiceClient;
import me.flyray.crm.core.entity.PlatformBase;
import me.flyray.crm.core.mapper.PlatformBaseMapper;
import me.flyray.crm.facade.request.PlatformBaseAddRequest;
import me.flyray.crm.facade.request.QueryMerchantBaseListRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import me.flyray.auth.common.config.UserAuthConfig;
import me.flyray.auth.common.util.jwt.IJWTInfo;
import me.flyray.auth.common.util.jwt.JWTHelper;
import me.flyray.common.biz.BaseBiz;
import me.flyray.common.enums.UserType;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.util.EntityUtils;

import tk.mybatis.mapper.entity.Example;

/**
 * 平台基础信息
 * @email ${email}
 * @date 2018-07-16 10:15:48
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PlatformBaseBiz extends BaseBiz<PlatformBaseMapper, PlatformBase> {
	
	private static Logger log = LoggerFactory.getLogger(PlatformBaseBiz.class);
	
	@Autowired
	private AdminUserServiceClient adminUserServiceClient;
    @Autowired
    private UserAuthConfig userAuthConfig;

	/**
	 * 1、向admin添加平台登陆用户
     * 2、向admin添加平台组织
     * 3、向admin在添加的平台组织下添加默认的角色（角色具有基础权限）
     * 4、添加平台基础数据
	 */
	public Map<String, Object> addPlatform(PlatformBaseAddRequest req) {
		log.info("添加平台请求参数：{}",EntityUtils.beanToMap(req));
		PlatformBase entity = new PlatformBase();
		BeanUtils.copyProperties(req,entity);
		Map<String, Object> result = new HashMap<String, Object>();
		PlatformBase platformBaseReq = new PlatformBase();
		platformBaseReq.setPlatformLoginName(entity.getPlatformLoginName());
		List<PlatformBase> platformBases = mapper.select(platformBaseReq);
		if (platformBases != null && platformBases.size() > 0) {
			throw new BusinessException(ResponseCode.PLATFORM_LOGIN_NAME_EXIST);
		}
		Map<String,Object> respMap = new HashMap<String, Object>();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("mobilePhone", req.getMobilePhone());
		if(!StringUtils.isEmpty(req.getMobilePhone())){
			respMap = adminUserServiceClient.queryByMobile(reqMap);
            if(!(ResponseCode.OK.getCode().equals(respMap.get("code")) && null == respMap.get("info"))){
                throw new BusinessException(ResponseCode.MOBILE_REPEAT);
            }
		}
        //添加平台
        long platformId = SnowFlake.getId();
        entity.setPlatformId(String.valueOf(platformId));
        //第一次添加都是"未认证状态"
        entity.setAuthenticationStatus("00");
        mapper.insert(entity);
        AddPlatformOrMerchantRequest request = new AddPlatformOrMerchantRequest();
        BeanUtils.copyProperties(req,request);
        request.setUserType(UserType.PLATFORM_ADMIN.getCode());
        Map<String,Object> reMap = adminUserServiceClient.addPlatformOrMerchant(request);
        String code = (String) reMap.get("code");
        if(ResponseCode.OK.getCode().equals(code)){
            result.put("code", ResponseCode.OK.getCode());
            result.put("message", ResponseCode.OK.getMessage());
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("code", reMap.get("code"));
            result.put("message", reMap.get("message"));
        }
		return result;
	}

	public TableResultResponse<PlatformBase> pageList(QueryMerchantBaseListRequest bean){
		log.info("查询平台列表请求参数：{}",EntityUtils.beanToMap(bean));
		Example example = new Example(PlatformBase.class);
		TableResultResponse tableResultResponse = null;
		if (bean.getPage() <= 0) {
			PlatformBase platformBase = new PlatformBase();
			platformBase.setPlatformLevel("02");
			List<PlatformBase> list = mapper.select(platformBase);
			tableResultResponse = new TableResultResponse<PlatformBase>(list.size(), list);
		} else {
			example.setOrderByClause("create_time desc");
			Page<PlatformBase> result = PageHelper.startPage(bean.getPage(), bean.getLimit());
			List<PlatformBase> list = mapper.selectByExample(example);
			tableResultResponse = new TableResultResponse<PlatformBase>(result.getTotal(), list);
		}
		return tableResultResponse;
	}
	
	/**
	 * 根据平台编号查询平台信息
	 * @author centerroot
	 * @time 创建时间:2018年8月16日上午10:15:57
	 * @param platformId
	 * @return
	 */
	public Map<String, Object> getOneObj(String platformId){
		log.info("【根据平台编号查询平台信息】   请求参数：platformId:{}",platformId);
		Map<String, Object> respMap = new HashMap<String, Object>();
		PlatformBase platformBaseReq = new PlatformBase();
		platformBaseReq.setPlatformId(platformId);
        List<PlatformBase> list = mapper.select(platformBaseReq);
		if (list != null && list.size() > 0) {
			PlatformBase platformBase = list.get(0);
			if (platformBase.getPlatformLogo() != null) {
				platformBase.setPlatformLogoStr(new String(platformBase.getPlatformLogo()));
			}
			respMap.put("platformBase", platformBase);
			respMap.put("code", ResponseCode.OK.getCode());
	        respMap.put("message", ResponseCode.OK.getMessage());
		} else {
			respMap.put("code", ResponseCode.SERVICE_NOT_AVALIABLE.getCode());
	        respMap.put("message", ResponseCode.SERVICE_NOT_AVALIABLE.getMessage());
		}
		
		log.info("【根据平台编号查询平台信息】   响应参数：{}",respMap);
		return respMap;
	}
	
	/**
	 * 根据序号删除平台
	 * @author centerroot
	 * @time 创建时间:2018年8月24日下午2:50:55
	 * @param id
	 * @return
	 */
	public Map<String, Object> deleteOne(Integer id){
		log.info("【根据序号删除平台信息】   请求参数：id:{}",id);
		Map<String, Object> respMap = new HashMap<String, Object>();
		PlatformBase platformBase = mapper.selectByPrimaryKey(id);
		
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("platformId", platformBase.getPlatformId());
		reqMap.put("platformName", platformBase.getPlatformName());
		reqMap.put("type", 2);
		respMap = adminUserServiceClient.deletePlatformOrMerchant(reqMap);
		mapper.deleteByPrimaryKey(id);
		
		log.info("【根据序号删除平台信息】   响应参数：{}",respMap);
		return respMap;
	}
	
	public Map<String, Object> updateObj(PlatformBaseAddRequest entity){
		log.info("【修改平台信息】   请求参数：{}",EntityUtils.beanToMap(entity));
		Map<String, Object> respMap = new HashMap<String, Object>();
		
		PlatformBase platformBase = new PlatformBase();
		BeanUtils.copyProperties(entity,platformBase);
		EntityUtils.setUpdatedInfo(platformBase);
	    mapper.updateByPrimaryKeySelective(platformBase);
	    Map<String,Object> reqMap = new HashMap<>();
	    reqMap.put("platformId", platformBase.getPlatformId());
	    reqMap.put("platformName", platformBase.getPlatformName());
	    respMap = adminUserServiceClient.updateDept(reqMap);
		
		log.info("【修改平台信息】   响应参数：{}",respMap);
		return respMap;
	}
	
}